<template>
	<view class="safe_tips">
		<van-notice-bar left-icon="info-o" wrapable text="点击查看安全生产检查表帮助文档" @click="goHelp" />
		<view class="form-list">
			<view class="form-item">
				<view class="form-label form-label-required">
					工程类型
				</view>
				<view class="form-value">
					<van-radio-group :value="form.proType" direction="horizontal" @change="onTypeChange">
						<van-radio name="1">小型工程</van-radio>
						<van-radio name="2">零星作业</van-radio>
					</van-radio-group>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					工程地点
				</view>
				<view class="form-value">
					<!-- <input v-model="form.address" class="form-input" /> -->
					<!-- <p v-if="form.address" class="form-input item-input" @click="toSelectAddress">
						{{ form.address ? form.address : "请选择工程地点" }}
					</p> -->
					<textarea class="form-input item-input" auto-height :value="form.address" disabled
						placeholder="请选择工程地点" @click="toSelectAddress" />
					<van-button v-if="pageType < 1" size="mini" style="margin-left: 32rpx;" @click="toSelectAddress">
						选择
					</van-button>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					房屋经纬度
				</view>
				<view class="form-value">
					<van-checkbox icon-size="28rpx" :value="posFlag" shape="square" @change="onPosFlagChange">
						是否更新
					</van-checkbox>
				</view>
			</view>

			<!-- 	<view class="form-item" v-if="posFlag">
				<view class="form-label form-label-required">
					经度
				</view>
				<view class="form-value">
					<input v-model="form.posY" class="form-input" disabled />
				</view>
			</view>

			<view class="form-item" v-if="posFlag">
				<view class="form-label form-label-required">
					纬度
				</view>
				<view class="form-value">
					<input v-model="form.posX" class="form-input" disabled />
				</view>
			</view> -->

			<view class="form-item">
				<view class="form-label form-label-required">
					工程名称
				</view>
				<view class="form-value">
					<input v-model="form.proName" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					建设方
				</view>
				<view class="form-value">
					<input v-model="form.builder" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					施工方
				</view>
				<view class="form-value">
					<input v-model="form.worker" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					施工内容
				</view>
				<view class="form-value">
					<textarea v-model="form.memo" style="height: 150rpx;" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					主要问题
				</view>
				<view class="form-value">
					<van-checkbox-group :value="form.problemsList" @change="onProblemChange">
						<van-checkbox v-for="(item,index) in problemLists" :name="item.name" :key="index">
							{{item.name}}
						</van-checkbox>
					</van-checkbox-group>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">
					其他不安全因素
				</view>
				<view class="form-value">
					<textarea v-model="form.other" style="height: 150rpx;" class="form-input" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					整改期限
				</view>
				<view class="form-value">
					<input disabled @click="openDeadLineTimePicker" v-model="form.deadline" class="form-input" />
					<van-popup :show="showDeadlineTimePicker" position="bottom" custom-style="height: 40%;"
						@close="onDeadLineTimePickerClose">
						<van-datetime-picker type="date" :min-date="minDate" :formatter="formatter"
							@confirm="deadLineConfirmDate" />
					</van-popup>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					检查日期
				</view>
				<view class="form-value">
					<input disabled @click="openCheckTimePicker" v-model="form.createTime" class="form-input" />
					<van-popup :show="showCheckTimePicker" position="bottom" custom-style="height: 40%;"
						@close="onCheckTimePickerClose">
						<van-datetime-picker type="date" :min-date="minDate" :formatter="formatter"
							@confirm="checkConfirmDate" />
					</van-popup>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					检查单位
				</view>
				<view class="form-value">
					<input v-model="form.creater" class="form-input" disabled />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					现场图片上传
				</view>
				<view class="form-value">
					<van-uploader :deletable="true" :file-list="form.docsList" :disabled="pageType > 0"
						@delete="deletePic" @after-read="afterDocRead" />
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					建设方或发包方单位现场负责人签名
				</view>
				<view class="form-value">
					<image @click="toBuilderSign" :src="builderSign" style="height: 150rpx;width: 50%;"
						class="form-input">
					</image>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					施工方或作业方现场负责人签字
				</view>
				<view class="form-value">
					<image @click="toWorkerSign" :src="workerSign" style="height: 150rpx;width: 50%;"
						class="form-input">
					</image>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label form-label-required">
					检查人签字
				</view>
				<view class="form-value">
					<image @click="toCheckSign" :src="createrSign" style="height: 150rpx;width: 50%;"
						class="form-input">
					</image>
				</view>
			</view>

			<view v-if="pageType < 1" class="form-item">
				<van-button size="small" type="info" @click="handleSubmit">
					提交
				</van-button>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		saveCheck,
		getProblems,
		getCheckById
	} from '@/request/api.js'
	export default {
		data() {
			return {
				pageType: 0,
				minDate: new Date().getTime(),
				posFlag: false,
				formatter: (type, value) => {
					if (type === 'year') {
						return `${value}年`
					}
					if (type === 'month') {
						return `${value}月`
					}
					return `${value}日`
				},
				createrSign: null,
				builderSign: null,
				workerSign: null,
				problemLists: [],
				showDeadlineTimePicker: false,
				showCheckTimePicker: false,
				form: {
					creater: '',
					createrSign: '',
					builderSign: '',
					workerSign: '',
					address: '',
					deadline: '', // 整改期限
					other: '', // 其他不安全因素
					builder: '', // 建设方
					worker: '', // 施工方
					proName: '', // 工程名称
					memo: '', // 施工内容
					proType: 1, // 工程类型
					problemsList: [],
					createTime: '', // 检查日期
					docsList: [] // 现场图片列表
				}
			};
		},
		onLoad(e) {
			this.init()
			this.pageType = e.pageType
			this.detailId = e.detailId
			if (this.pageType > 0) {
				this.detailId = e.detailId
				this.getData()
			} else {
				var aData = new Date()
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				this.value = aData.getFullYear() + "-" + month + "-" + date;
				this.form.createTime = aData.getFullYear() + "/" + month + "/" + date;
			}
		},
		methods: {
			onPosFlagChange(e) {
				if (e.detail) {
					uni.getLocation({
						type: 'wgs84',
						success: (res) => {
							this.$set(this.form, 'posX', res.longitude)
							this.$set(this.form, 'posY', res.latitude)
						}
					})
				}
				this.posFlag = e.detail
			},

			deletePic(index) {
				this.form.docsList.splice(index, 1)
			},

			goHelp() {
				uni.downloadFile({
					url: this.$config.baseUrl + '/help/jc.doc',
					success: (res) => {
						uni.showToast({
							title: '正在打开帮助文档'
						})
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								console.log('打开文档成功');
							}
						});
					},
					fail: () => {
						uni.showToast({
							icon: 'none',
							title: '文件下载失败'
						})
					}
				})
			},

			getData() {
				getCheckById({
					Id: this.detailId
				}).then(res => {
					this.form = {
						...this.form,
						...res.data[0]
					}
					this.builderSign = this.form.builderSign
					this.workerSign = this.form.workerSign
					this.createrSign = this.form.createrSign
					this.form.proType = this.form.proType + ''
					this.form.deadline = this.form.deadline.substring(0, 10).replaceAll('-', '/');
					this.form.createTime = this.form.createTime.substring(0, 10).replaceAll('-', '/');
					for (let problemIndex = 0; problemIndex < this.form.problemsList.length; problemIndex++) {
						const problemItem = this.form.problemsList[problemIndex]
						this.form.problemsList[problemIndex] = problemItem.name
					}
					for (let docIndex = 0; docIndex < this.form.docsList.length; docIndex++) {
						const docItem = this.form.docsList[docIndex]
						docItem.url = docItem.path
						docItem.deletable = false
						// this.form.docsList[docIndex]['url'] = docItem.
					}
				})
			},

			deadLineConfirmDate(e) {
				var aData = new Date(parseInt(e.detail))
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				this.value = aData.getFullYear() + "-" + month + "-" + date;
				this.form.deadline = aData.getFullYear() + "/" + month + "/" + date;
				this.showDeadlineTimePicker = false
			},

			checkConfirmDate(e) {
				var aData = new Date(parseInt(e.detail))
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				this.value = aData.getFullYear() + "-" + month + "-" + date;
				this.form.createTime = aData.getFullYear() + "/" + month + "/" + date;
				this.showCheckTimePicker = false
			},

			openCheckTimePicker() {
				this.showCheckTimePicker = true
			},

			onCheckTimePickerClose() {
				this.showCheckTimePicker = false
			},

			openDeadLineTimePicker() {
				this.showDeadlineTimePicker = true
			},

			onDeadLineTimePickerClose() {
				this.showDeadlineTimePicker = false
			},

			afterDocRead(event) {
				const {
					file
				} = event.detail;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				uni.uploadFile({
					url: this.$config.uploadUrl,
					filePath: file.url,
					name: 'file',
					formData: {
						filetype: "image",
					},
					success: (res) => {
						// 上传完成需要更新 fileList
						const {
							result
						} = JSON.parse(res.data)
						this.form.docsList.push({
							...file,
							url: result,
							deletable: true
						});
					},
				});
			},

			init() {
				this.getProblemLists()
				uni.getStorage({
					key: 'userInfo',
					success: (res) => {
						const {
							account,
							userName,
							deptName
						} = res.data[0]
						this.form.creater = userName
						this.form.userID = account
					}
				})
			},

			getProblemLists() {
				getProblems().then(res => {
					this.problemLists = res.result
				})
			},

			onProblemChange(e) {
				this.form.problemsList = e.detail
			},

			onTypeChange(e) {
				this.form.proType = e.detail
			},

			toSelectAddress() {
				if (this.pageType < 1) {
					uni.$on('handleSelectAddress', (item) => {
						this.$set(this.form, 'address', item.address)
						this.$set(this.form, 'houseID', item.houseID)
						if (item.bApply) {
							this.$set(this.form, 'proName', item.proName)
							this.$set(this.form, 'worker', item.worker)
							this.$set(this.form, 'builder', item.builder)
							this.$set(this.form, 'applyID', item.applyID)
						}
					})
					uni.navigateTo({
						url: '../select_project_address/select_project_address?pageType=1&needSheQu=false'
					})
				}
			},

			handleSubmit() {
				const values = Object.values(this.form)
				const keys = Object.keys(this.form)
				let requiredFlag = true
				for (let valueIndex = 0; valueIndex < values.length; valueIndex++) {
					const valueItem = values[valueIndex]
					const keyItem = keys[valueIndex]
					if (keyItem === 'other') continue // 跳过，不必填
					if (keyItem === 'posY') continue // 跳过，不必填
					if (keyItem === 'posX') continue // 跳过，不必填
					const itemlength = (typeof valueItem === 'number') ? valueItem : valueItem.length
					if (itemlength <= 0) {
						requiredFlag = false
						break
					}
					// console.log(valueItem, (typeof valueItem === 'number') ? valueItem : valueItem.length)
				}
				if (!requiredFlag) {
					uni.showToast({
						icon: 'none',
						title: '请完成所有必填项后再提交'
					})
					return
				}
				if (this.pageType < 1 && this.form.hasOwnProperty('bApply')) {
					delete this.form.bApply
				}
				for (let problemIndex = 0; problemIndex < this.form.problemsList.length; problemIndex++) {
					// 处理问题字段
					const problemItem = this.form.problemsList[problemIndex]
					const tempItemObj = {}
					tempItemObj['name'] = problemItem
					tempItemObj['checked'] = true
					this.form.problemsList[problemIndex] = tempItemObj
				}
				for (let docsIndex = 0; docsIndex < this.form.docsList.length; docsIndex++) {
					// 处理问题字段
					const docsItem = this.form.docsList[docsIndex]
					const tempItemObj = {}
					tempItemObj['name'] = docsItem.url
					tempItemObj['path'] = docsItem.url
					this.form.docsList[docsIndex] = tempItemObj
				}
				saveCheck(this.form).then(res => {
					uni.$emit('refreshCheck')
					uni.navigateBack({
						delta: 1
					})
				})
			},

			saveSign(data) {
				console.log(data)
			},

			toCheckSign() {
				uni.$on('handleSaveSign', ({
					tempPath,
					callBackType
				}) => {
					console.log(tempPath, callBackType)
					if (callBackType === 'toCheckSign') {
						console.log('收到了更新', tempPath)
						this.createrSign = tempPath
						uni.showLoading({
							title: '正在上传签名'
						})
						uni.uploadFile({
							url: this.$config.uploadUrl,
							filePath: tempPath,
							name: "file",
							formData: {
								filetype: "image",
							},
							success: (res) => {
								uni.hideLoading()
								const {
									result
								} = JSON.parse(res.data) // result就是后端返回的图片地址
								this.form.createrSign = result
							},
							fail: (e) => {
								uni.hideLoading()
								uni.showToast({
									icon: 'none',
									title: '签名上传失败'
								})
							}
						})
					}
				})
				uni.navigateTo({
					url: '../sign_page/sign_page?callback=toCheckSign'
				})
			},

			toWorkerSign() {
				uni.$on('handleSaveSign', ({
					tempPath,
					callBackType
				}) => {
					console.log(callBackType)
					if (callBackType === 'toWorkerSign') {
						console.log('收到了更新', tempPath)
						this.workerSign = tempPath
						uni.showLoading({
							title: '正在上传签名'
						})
						uni.uploadFile({
							url: this.$config.uploadUrl,
							filePath: tempPath,
							name: "file",
							formData: {
								filetype: "image",
							},
							success: (res) => {
								uni.hideLoading()
								const {
									result
								} = JSON.parse(res.data) // result就是后端返回的图片地址
								this.form.workerSign = result
							},
							fail: (e) => {
								uni.hideLoading()
								uni.showToast({
									icon: 'none',
									title: '签名上传失败'
								})
							}
						})
					}
				})
				uni.navigateTo({
					url: '../sign_page/sign_page?callback=toWorkerSign'
				})
			},

			toBuilderSign() {
				uni.$on('handleSaveSign', ({
					tempPath,
					callBackType
				}) => {
					if (callBackType === 'toBuilderSign') {
						console.log('收到了更新', tempPath)
						this.builderSign = tempPath
						uni.showLoading({
							title: '正在上传签名'
						})
						uni.uploadFile({
							url: this.$config.uploadUrl,
							filePath: tempPath,
							name: "file",
							formData: {
								filetype: "image",
							},
							success: (res) => {
								uni.hideLoading()
								const {
									result
								} = JSON.parse(res.data) // result就是后端返回的图片地址
								this.form.builderSign = result
							},
							fail: (e) => {
								uni.hideLoading()
								uni.showToast({
									icon: 'none',
									title: '签名上传失败'
								})
							}
						})
					}
				})
				uni.navigateTo({
					url: '../sign_page/sign_page?callback=toBuilderSign'
				})
			}
		}
	}
</script>

<style lang="scss">
	.safe_tips {
		.form-list {
			padding: 32rpx;
			box-sizing: border-box;

			.form-item {
				display: flex;
				align-items: flex-start;
				justify-content: center;
				margin-bottom: 32rpx;

				.form-label {
					width: 150rpx;
					margin-right: 32rpx;
					font-size: 28rpx;
					color: #141414;
				}

				.form-label-required {
					&::before {
						content: "*";
						color: red;
						margin-right: 6rpx;
					}
				}

				.form-value {
					font-size: 28rpx;
					color: #141414;
					flex: 1;
					width: 0;
					display: flex;
					align-items: center;

					.form-input {
						padding: 0 16rpx;
						box-sizing: border-box;
						border: 1px solid #CECECE;
					}
				}
			}
		}
	}
</style>
